package cn.gailvlun.gll.net;

import android.support.annotation.Nullable;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.CompletableObserver;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;



public abstract class HttpSubscriber<T> implements Observer<T> {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
        onFinish();
    }

    @Override
    public void onError(Throwable e) {
        
        onFailure(parseThrowable(e), null, getErrorCode(e));
        onFinish();
    }

    private String parseThrowable(Throwable e) {
        if (e instanceof HttpException) {
            try {
                String body = ((HttpException) e).response().errorBody().string();
                Response res = GsonUtil.getGson().fromJson(body, Response.class);
                return res.getDetail();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            if (((HttpException) e).response().code() >= 500) {
                return "服务器内部错误";
            }
        } else if (e instanceof SocketTimeoutException) {
            return "服务器连接超时";
        } else if (e instanceof UnknownHostException) {
            return "网络未连接";
        }
        return "未知错误";
    }

    private int getErrorCode(Throwable e) {
        if (e instanceof HttpException) {
            return ((HttpException) e).response().code();
        }
        return 400;
    }

    @Override
    public void onComplete() {}

    protected abstract void onSuccess(T response);
    protected abstract void onFailure(String errMsg, @Nullable T response, int code);
    protected void onFinish() {}
}
